﻿using STMS.BLL;
using STMS.Models.DModels;
using STMS.STMSApp.FModels;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using CaptureVideoTest;
using Emgu.CV;
using CJLU.WLGZJLJZ;

namespace STMS.STMSApp.DZPDCheck
{
    public partial class FrmDZPDLoad : Form
    {
        public static string MF;
        public static string MF1;
        public static string AF = "40";
        public static string Station;
        string loaction = "127.0.0.1";
        //ClsCameraHelper cam = new ClsCameraHelper();
        string detectDIG = "";
        public FrmDZPDLoad()
        {
            InitializeComponent();
        }
        DZPDBLL dzpdBLL = new DZPDBLL();
        MEABLL meaBLL = new MEABLL();

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void uCircleButton1_MouseEnter(object sender, EventArgs e)
        {
            uCircleButton1.ForeColor = Color.White;
        }

        private void uCircleButton1_MouseLeave(object sender, EventArgs e)
        {
            uCircleButton1.ForeColor = Color.FromArgb(45, 50, 116);
        }

        private void FrmDZPDLoad_Load(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;
        }

        

        //载入现有电子皮带秤期间核查数据
        private void LoadDZPDHistorList()
        {
            //加载数据 到数据库读取数据
            string station = cboDZPDStation.Text;
            string keywords = txtTimeSelect.Text;
            List<HistorInfo> dzpdHistorList = dzpdBLL.GetHistorInfos(keywords, station);
            if(dzpdHistorList.Count>0)
            {
                dgvDZPDCheckList.AutoGenerateColumns = false;
                dgvDZPDCheckList.DataSource = dzpdHistorList;
                SetEnableBtns(true);
            }
            else
            {
                dgvDZPDCheckList.DataSource = null;
                SetEnableBtns(false);
            }
        }
        private void SetEnableBtns(bool blShow)
        {
            //uPageBtnSearch.Enabled = blShow;
        }

        private void uPageBtnSearch_Click(object sender, EventArgs e)
        {
            LoadDZPDHistorList();
        }

        private void uPageBtnDZPDCheck_Click(object sender, EventArgs e)
        {
            if (comboBox_guige.Text == "模式一（5kg）")
            {
                AF = "100";
            }
            else if (cboDZPDStation.Text == "模式一（2kg）")
            {
                AF = "40";
            }
            MF = (Convert.ToDouble(MF1)-Convert.ToDouble(MF)).ToString("#0.0000");
            Station = cboDZPDStation.Text;
            ShowDZPDInfoPage(1, 0);
        }
        /// <summary>
        /// 打开电子皮带秤操作信息页
        /// </summary>
        /// <param name="actType"></param>
        /// <param name="dzpdId"></param>
        private void ShowDZPDInfoPage(int actType,int dzpdId)
        {
            FrmDZPDInfo fDZPD = new FrmDZPDInfo();
            fDZPD.Tag = new FInfoData()
            {ActType = actType,FId = dzpdId};
            //刷新列表页数据效果 采用事件
            fDZPD.ReLoadList +=()=> LoadDZPDHistorList();
            fDZPD.StartPosition = FormStartPosition.CenterScreen;
            fDZPD.ShowDialog();
        }
        /// <summary>
        /// 行内操作按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvDZPDCheckList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var cell = dgvDZPDCheckList.Rows[e.RowIndex].Cells[e.ColumnIndex];//获取当前点击的单元格
            string headText = cell.FormattedValue.ToString();
            HistorInfo ObjectRow = dgvDZPDCheckList.Rows[e.RowIndex].DataBoundItem as HistorInfo;
            switch(headText)
            {
                case "删除":
                    DeleteDZPDInfo(ObjectRow);
                    break;
                case "修改":
                    //打开仓库信息页
                    ShowDZPDInfoPage(2, ObjectRow.R_ID);
                    break;
                
            }
        }
        /// <summary>
        /// 行内删除方法封装
        /// </summary>
        /// <param name="dzpdInfo"></param>
        private void DeleteDZPDInfo(HistorInfo dzpdInfo)
        {
            String InfoName = "电子皮带秤核查信息";
            string delName = "删除";
            DialogResult dr =  MsgBoxHelper.MsgBoxConfirm($"{InfoName}删除", $"确定要删除当前信息吗?");
            if(dr == DialogResult.Yes)
            {
                bool bl = dzpdBLL.DeleteDZPDInfo(dzpdInfo.R_ID);
                if(bl)
                {
                    MsgBoxHelper.MsgBoxShow($"{InfoName}删除", $"已成功删除！");
                    LoadDZPDHistorList();
                }
                else
                {
                    MsgBoxHelper.MsgBoxShow($"{InfoName}删除", $"删除失败！");
                    return;
                }
            }
        }

        private void uCircleButton1_Click(object sender, EventArgs e)
        {
            LoadDZPDHistorList();
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
        {

        }

        private void uPBtn_start_Click(object sender, EventArgs e)
        {
            string station = cboDZPDStation.Text;
            if (comboBox_model.Text == "相机模式")
            {
                //开始核查前图像识别
                //ClsCameraHelper cam = new ClsCameraHelper();
                //if (false == FrmMain.cam.Open())
                //{
                //    MessageBox.Show("请打开摄像头", "警告",
                //    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //    return;
                //}
                Mat img = new Mat();
                while (img.IsEmpty == true)
                {
                    FrmMain.cam.getImg().CopyTo(img);
                }
                FormDetect formDetect1 = new FormDetect(img);
                formDetect1.ShowDialog();
                if (formDetect1.DialogResult == DialogResult.OK)
                {
                    detectDIG = formDetect1.m_strResult;
                    MF = detectDIG;
                }
            }
            else
            {
                List<MeasurelInfo> mf = meaBLL.GetMeasurelInfos("1", station);
                MF = Convert.ToString(mf[0].V_DATA);             
            }
            text_currtF.Text = MF;

            if (comboBox_guige.Text == "模式一（5kg）")
            {
                var socketM5 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                //2 建立连接
                socketM5.Connect(new IPEndPoint(IPAddress.Parse(loaction), 502));

                //值的转换
                short value5 = 1;//脚本id
                var values5 = BitConverter.GetBytes(value5).Reverse().ToArray();

                //3 获取并发送命令（寄存器起始地址、站号、功能码）
                var command5 = GetWriteCommand(544, values5, 2, 16);
                socketM5.Send(command5);
                //4 关闭连接
                socketM5.Shutdown(SocketShutdown.Both);
                socketM5.Close();
            }
            else
            {
                var socketM2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                //2 建立连接
                socketM2.Connect(new IPEndPoint(IPAddress.Parse(loaction), 502));

                //值的转换
                short value2 = 2;//脚本id
                var values2 = BitConverter.GetBytes(value2).Reverse().ToArray();

                //3 获取并发送命令（寄存器起始地址、站号、功能码）
                var command2 = GetWriteCommand(544, values2, 2, 16);
                socketM2.Send(command2);
                //4 关闭连接
                socketM2.Shutdown(SocketShutdown.Both);
                socketM2.Close();
            }
            //1 创建Socket,写入1到0x0228
            var socketFirst = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //2 建立连接
            socketFirst.Connect(new IPEndPoint(IPAddress.Parse(loaction), 502));

            //值的转换
            short valueFirst = 1;
            var valuesFirst = BitConverter.GetBytes(valueFirst).Reverse().ToArray();

            //3 获取并发送命令（寄存器起始地址、站号、功能码）
            var commandFirst = GetWriteCommand(552, valuesFirst, 2, 16);
            socketFirst.Send(commandFirst);
            //4 关闭连接
            socketFirst.Shutdown(SocketShutdown.Both);
            socketFirst.Close();

            //1 创建Socket
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //2 建立连接
            socket.Connect(new IPEndPoint(IPAddress.Parse(loaction), 502));

            //值的转换
            short value = 2;
            var values = BitConverter.GetBytes(value).Reverse().ToArray();

            //3 获取并发送命令（寄存器起始地址、站号、功能码）
            var command = GetWriteCommand(552, values, 2, 16);
            socket.Send(command);
            //4 关闭连接
            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
            Thread receiveThread = new Thread(GetResponse);
            receiveThread.Start();           
        }
        public static byte[] GetWriteCommand(ushort address, byte[] values, byte stationNumber, byte functionCode)
        {
            byte[] buffer = new byte[13 + values.Length];
            buffer[0] = 0x19;
            buffer[1] = 0xB2;//检验信息，用来验证response是否串数据了           
            buffer[4] = BitConverter.GetBytes(7 + values.Length)[1];
            buffer[5] = BitConverter.GetBytes(7 + values.Length)[0];//表示的是header handle后面还有多长的字节

            buffer[6] = stationNumber; //站号
            buffer[7] = functionCode;  //功能码
            buffer[8] = BitConverter.GetBytes(address)[1];
            buffer[9] = BitConverter.GetBytes(address)[0];//寄存器地址
            buffer[10] = (byte)(values.Length / 2 / 256);
            buffer[11] = (byte)(values.Length / 2 % 256);//写寄存器数量(除2是一个寄存器两个字节，寄存器16位。除以256是byte最大存储255。)              
            buffer[12] = (byte)(values.Length);          //写字节的个数
            values.CopyTo(buffer, 13);                   //把目标值附加到数组后面
            return buffer;
        }
        public static byte[] GetReadCommand(ushort address, byte stationNumber, byte functionCode, ushort length)
        {
            byte[] buffer = new byte[12];
            buffer[0] = 0x19;
            buffer[1] = 0xB2;//Client发出的检验信息
            buffer[2] = 0x00;
            buffer[3] = 0x00;//表示tcp/ip 的协议的modbus的协议
            buffer[4] = 0x00;
            buffer[5] = 0x06;//表示的是该字节以后的字节长度

            buffer[6] = stationNumber;  //站号
            buffer[7] = functionCode;   //功能码
            buffer[8] = BitConverter.GetBytes(address)[1];
            buffer[9] = BitConverter.GetBytes(address)[0];//寄存器地址
            buffer[10] = BitConverter.GetBytes(length)[1];
            buffer[11] = BitConverter.GetBytes(length)[0];//表示request 寄存器的长度(寄存器个数)
            return buffer;
        }
        public void  GetResponse()
        {          
            short value1 = -1;
            string station = cboDZPDStation.Text;
            while (Convert.ToString(value1) != "9")
            {
                Thread.Sleep(2000);
                //1 创建Socket1
                var socket1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //2 建立连接
                socket1.Connect(new IPEndPoint(IPAddress.Parse(loaction), 502));


                //3 获取命令[组装请求报文]（寄存器起始地址：4、站号：2、功能码：3、读取寄存器长度：1）
                byte[] command1 = GetReadCommand(554, 2, 3, 1);

                //4 发送命令
                socket1.Send(command1);
                //5 读取响应
                byte[] buffer1 = new byte[8];//先读取前面八个字节（Map报文头）
                socket1.Receive(buffer1, 0, buffer1.Length, SocketFlags.None);

                //5.1 获取将要读取的数据长度
                int length = buffer1[4] * 256 + buffer1[5] - 2;//减2是因为这个长度数据包括了单元标识符和功能码，占两个字节

                //5.2 读取数据
                byte[] buffer2 = new byte[length];
                var readLength2 = socket1.Receive(buffer2, 0, buffer2.Length, SocketFlags.None);

                byte[] buffer3 = new byte[readLength2 - 1];
                //5.3  过滤第一个字节（第一个字节代表数据的字节个数）
                Array.Copy(buffer2, 1, buffer3, 0, buffer3.Length);
                var buffer3Reverse = buffer3.Reverse().ToArray();
                value1 = BitConverter.ToInt16(buffer3Reverse, 0);
                //6 关闭连接
                socket1.Shutdown(SocketShutdown.Both);
                socket1.Close();               
            }
            if (comboBox_model.Text == "相机模式")
            {
                //监测到核查完成，后续图像识别
                //if (false == FrmMain.cam.Open())
                //{
                //    MessageBox.Show("请打开摄像头", "警告",
                //    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //    return;
                //}
                Mat img = new Mat();
                while (img.IsEmpty == true)
                {
                    FrmMain.cam.getImg().CopyTo(img);
                }
                FormDetect formDetect = new FormDetect(img);
                formDetect.ShowDialog();
                if (formDetect.DialogResult == DialogResult.OK)
                {
                    detectDIG = formDetect.m_strResult;
                    MF1 = detectDIG;
                    MessageBox.Show("本次核查完成，请确认上传！");
                }
            }
            else
            {  
                List<MeasurelInfo> mf = meaBLL.GetMeasurelInfos("1", station);
                MF1 = Convert.ToString(mf[0].V_DATA);
                MessageBox.Show("本次核查完成，请确认上传！");
            }
            text_currtF.Text = MF1;
            //1 创建Socket
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //2 建立连接
            socket.Connect(new IPEndPoint(IPAddress.Parse(loaction), 502));

            //值的转换
            short value = 0;
            var values = BitConverter.GetBytes(value).Reverse().ToArray();

            //3 获取并发送命令（寄存器起始地址、站号、功能码）
            var command = GetWriteCommand(554, values, 2, 16);
            socket.Send(command);
            //4 关闭连接
            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
            
            
        }

        private void uPBtn_stop_Click(object sender, EventArgs e)
        {
            //1 创建Socket
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //2 建立连接
            socket.Connect(new IPEndPoint(IPAddress.Parse(loaction), 502));

            //值的转换
            short value = 3;
            var values = BitConverter.GetBytes(value).Reverse().ToArray();

            //3 获取并发送命令（寄存器起始地址、站号、功能码）
            var command = GetWriteCommand(552, values, 2, 16);
            socket.Send(command);
            //4 关闭连接
            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
        }



        private void uPanel1_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}
